package database

import (
	"fmt"

	"go.etcd.io/bbolt"
)

type BBolt struct {
	*bbolt.DB
}

func NewBBolt(path string) (*BBolt, error) {
	db, err := bbolt.Open(path, 0600, nil)
	if err != nil {
		return nil, fmt.Errorf("bbolt: %w", err)
	}
	return &BBolt{DB: db}, nil
}

func (b *BBolt) Put(Bucket, key, value []byte) error {
	return b.Update(func(tx *bbolt.Tx) error {
		bucket, err := tx.CreateBucketIfNotExists(Bucket)
		if err != nil {
			return fmt.Errorf("BBolt.Put: %w", err)
		}
		return bucket.Put(key, value)
	})
}

func (b *BBolt) Get(Bucket, key []byte) ([]byte, error) {
	var value []byte
	err := b.View(func(tx *bbolt.Tx) error {
		bucket := tx.Bucket(Bucket)
		if bucket == nil {
			return nil
		}
		value = bucket.Get(key)
		return nil
	})
	if err != nil {
		return nil, fmt.Errorf("BBolt.Get: %w", err)
	}
	return value, nil
}
